package com.dragon.concurrent.demo.waitnotify;

import java.util.stream.IntStream;
import java.util.stream.Stream;

public class ProduceConsumeVersion3 {

    private int i = 0;

    private final Object LOCK = new Object();

    private volatile boolean isProduced = false;

    public void produce() {
        synchronized (LOCK) {
            while (isProduced) {
                try {
                    LOCK.wait();
                } catch (Exception e) {

                }
            }
            System.out.println("P->" + ++i);
            isProduced = true;
            LOCK.notifyAll();
        }
    }

    public void consume() {
        synchronized (LOCK) {
            while (!isProduced) {
                try {
                    LOCK.wait();
                } catch (Exception e) {

                }
            }
            System.out.println("C->" + i);
            isProduced = false;
            LOCK.notifyAll();
        }
    }

    public static void main(String[] args) {
        ProduceConsumeVersion3 produceConsumeVersion3 = new ProduceConsumeVersion3();
        Stream.of("p1", "p2", "p3")
                .forEach(s -> {
                    new Thread(() -> {
                        while (true) {
                            produceConsumeVersion3.produce();
                        }
                    }, s).start();
                });

        Stream.of("c1", "c2")
                .forEach(s -> {
                    new Thread(() -> {
                        while (true) {
                            produceConsumeVersion3.consume();

                        }
                    }, s).start();
                });

    }
}
